package com.springboot.controller;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.po.*;
import com.springboot.service.*;

@RestController
@RequestMapping(path = "/OrdersController" , method = RequestMethod.POST)
public class OrdersController {
	@Autowired
	OrdersService ordersService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	CouponService couponService;
	
	@RequestMapping("/CreateOrders")
	public int createOrders(Orders orders) throws Exception{
		//返回订单ID
		return ordersService.createOrders(orders);
	}
	
	@RequestMapping("/getOrdersById")
	public Orders getOrdersById(Integer orderId) throws Exception{
		return ordersService.getOrdersById(orderId);
	}
	
	@RequestMapping("/listOrdersByUserId")
	public List<Orders> listOrdersByUserId(String userId)throws Exception {
		return ordersService.listOrdersByUserId(userId);
	}
	
	//添加功能：
	@RequestMapping("/updateOrderState")
	@Transactional
//	public int updateOrderState(@RequestParam("orderId") String orderId, @RequestParam("orderState") Integer orderState) throws Exception{
	public int updateOrderState(Integer orderId, Integer orderState , Integer typeId) throws Exception{
		if(orderState == null || orderId == null) {
			//拦截非法参数，mapper会报：Cannot invoke "java.lang.Integer.intValue()" because "orderState" is null
			return 0;
		}
		if(typeId != null) {
			//使用优惠券
			//更新用户的优惠券数量
			Orders orders = ordersService.getOrdersById(orderId);
			Coupon coupon = couponService.getCoupon(typeId);
			BigDecimal del = coupon.getValues();
			BigDecimal oldTotal = orders.getOrderTotal();
			BigDecimal newtotal = oldTotal.subtract(del);
			
			String userId = orders.getUserId();
			//使用优惠券需要更改订单金额
//			ordersService.setOrderTotal(orderId , newtotal);
			
			userCouponService.updateUserCounpon(userId, typeId);	
		}
		//不使用优惠券就单独改变订单状态即可
		//serviceImpl里面进行参数检验
		return ordersService.updateOrderState(orderId, orderState);
		//返回值是0代表改变失败，1成功
	}
	
}
